package top.kaoshanji.p1ch02c;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/1/2 19:07
 */
public class MethodHandleExample02 {

    private static final Logger logger = LogManager.getLogger(MethodHandleExample02.class);

    public static void main(String[] args) throws Throwable {

        MethodHandleExample02 example = new MethodHandleExample02();

        example.asVarargsCollector();

        example.asCollector();

    }

    public void asVarargsCollector() throws Throwable {
        logger.info("...代码清单 p1ch02c-07：MethodHandle#asVarargsCollector的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mh = lookup.findVirtual(MethodHandleExample02.class, "normalMethod",
                MethodType.methodType(void.class, String.class, int.class, int[].class));

        mh = mh.asVarargsCollector(int[].class);
        mh.invoke(this, "Hello", 2, 3, 4, 5);

        System.out.println(mh.type());
    }

    public void asCollector() throws Throwable {
        logger.info("...代码清单 p1ch02c-08：MethodHandle#asCollector的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mh = lookup.findVirtual(MethodHandleExample02.class, "normalMethod",
                MethodType.methodType(void.class, String.class, int.class, int[].class));

        mh = mh.asCollector(int[].class, 2);
        mh.invoke(this, "Hello", 2, 3, 4);

        System.out.println(mh.type());

    }

    public void normalMethod(String arg1, int arg2, int[] arg3) {}

}
